package com.zcm.controller.authorize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.zcm.service.ServiceFactory;
import com.zcm.service.ServiceName;
import com.zcm.service.auth.AuthorizeService;
import com.zcm.service.auth.impl.AccessToken;
import com.zcm.service.auth.impl.RequestToken;
import com.zcm.service.weibo.LoadServices;
import com.zcm.service.weibo.load.UserLoadOperators;

public class SinaWeiboAuthorizeController implements Controller {
	
	private String authorizationType;
	
	private RequestToken reqToken;	
	
	private ServiceFactory serviceFactory;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {	

		AuthorizeService authorizeService = this.serviceFactory.getService(ServiceName.AUTHORIZE_SINA.toString());
		
		if(request.getParameter("oauth_verifier") != null) {
			String oauth_verifier = request.getParameter("oauth_verifier");
			this.reqToken.setOauthVerifier(oauth_verifier);
			System.out.println(reqToken.getTokenSecret());
			AccessToken accessToken = authorizeService.getAccessToken(this.reqToken);
			
			this.test(accessToken);
			return null;
		} else {
			RequestToken reqToken = authorizeService.getRequestToken();	
			this.reqToken = reqToken;
			String authorizationUrl = authorizeService.getAuthorizationURL(reqToken);
			response.sendRedirect(authorizationUrl);
			return null;	
		}
	}
	
	private void test(AccessToken accessToken) {
		 LoadServices loadService = this.serviceFactory.getService(ServiceName.LOAD_SERVICE.toString());
		 UserLoadOperators userOpt = loadService.getUserLoadOperators();
		 userOpt.loadUserInfo(accessToken.getUid(), accessToken);
	} 

	public ServiceFactory getServiceFactory() {
		return serviceFactory;
	}

	public void setServiceFactory(ServiceFactory serviceFactory) {
		this.serviceFactory = serviceFactory;
	}
}
